var express = require('express');
var router = express.Router();
var db = require("../util/DataBase.js")

var topicService = require("../service/topic.js");

/* GET users listing. */
router.get('/all', function(req, res, next) {

  db.query("SELECT `id`, `name`, `cover_url` FROM `topic`", function(err, results) {
      if(err)
      {
          res.json(null, -1, "获取话题失败")
          return;
      }
      res.json(results);

  });


});

/* GET users listing. */
router.get('/follow/list', function(req, res, next) {

  topicService.getFollowTopic(req.session.user.id, (followTopicList) => {
    res.json(followTopicList);
  }, () => {
    res.json(null, -1, "获取关注话题列表失败");
  });

});

router.post('/follow/update', function(req, res, next) {

  var body = req.body;

  var topicIdList = body.topicIdList;
  var userId = req.session.user.id;

  var insertNum = topicIdList.length;

  var insertComplete = 0;

  topicService.removeAllFollow(userId, () => {

    for(var i = 0; i < insertNum; ++ i)
    {

      let values = [
        userId,
        topicIdList[i]
      ];

      db.query("INSERT INTO `follow_user_topic` (`user_id`, `topic_id`) VALUES (?, ?)", values, function(err, results) {

        if(err)
        {
          res.json(null, -1, "更新关注主题失败")
        }
        else
        {
          if(++ insertComplete == insertNum)
          {
            res.json(null);
          }
        }

      });
    }

  }, () => {
    res.json(null, -2, "删除原有关注话题失败")
  });



});

module.exports = router;
